package com.easou.ps.master.query.qs;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.easou.ps.common.servicehandle.Constants;
import com.easou.ps.common.servicehandle.ServiceAddress;
import com.easou.ps.common.servicehandle.ServiceGroup;
import com.easou.ps.common.servicehandle.ServiceGroupShard;
import com.easou.ps.common.servicehandle.ServicePool;
import com.easou.ps.master.kit.ConfigFactory;

public class QSProxyFactory {
	static final Logger LOG = Logger.getLogger("query");
	static ServicePool pool = new ServicePool("QS", ConfigFactory.getSysConfig().getInt("qs.connection.num", 1), 0, true);
	static ConcurrentHashMap<ServiceAddress, QSProxy> proxyMap = new ConcurrentHashMap<ServiceAddress, QSProxy>();
	
	static QSProxy getProxy(ServiceAddress address) {
		QSProxy proxy = proxyMap.get(address);
		if (proxy == null) {
			proxy = new QSProxy(address);
			QSProxy old = proxyMap.putIfAbsent(address, proxy);
			if (old != null) {
				proxy = old;
			}
		}
		return proxy;
	}
	
	/**
	 * 启动初始化时调用
	 * @param address
	 */
	public static void putServiceAddress(ServiceAddress address) {
		pool.putAddress("QS", address);
	}
	
	public static QSProxy getProxy() {
		ServiceAddress addr = pool.selectAddress("QS");
		if (addr == null) {
			LOG.error("QS unavailable");
			return null;
		}
		return getProxy(addr);
	}
	
	public static boolean setOnline(String host, int port, boolean online) {
		if (online) {
			return pool.setOnline(host, port);
		} else {
			return pool.setOffline(host, port);
		}
	}
	
	public static List<ServiceAddress> getServiceAddresses() {
		List<ServiceAddress> ret = new ArrayList<ServiceAddress>();
		ServiceGroup group = pool.getGroup("QS");
		ServiceGroupShard shard = group.getShard(Constants.DEFAULT_SHARD_LABEL);
		List<ServiceAddress> addresses = shard.getReplicas();
		for (ServiceAddress addr : addresses) {
			if (addr != null) {
				ret.add(addr);
			}
		}
		return ret;
	}
}
